package com.you.rpc.client;

import com.you.rpc.entity.ResponseCommand;
import com.you.rpc.entity.RpcAddress;
import com.you.rpc.until.AddressUtil;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;

@Slf4j
public class ClientHandler extends SimpleChannelInboundHandler<Object> {

    private Map<RpcAddress, ChannelFuture> connections;
    private Map<Integer, InvokeFuture> invokeFutureMap;


    public ClientHandler(Map<RpcAddress, ChannelFuture> connections, Map<Integer, InvokeFuture> invokeFutureMap) {
        this.connections = connections;
        this.invokeFutureMap = invokeFutureMap;
    }


    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("接受响应: {} ", msg);
        ResponseCommand responseCommand = (ResponseCommand) msg;
        int id = responseCommand.getId();
        if (invokeFutureMap.containsKey(id)) {
            InvokeFuture invokeFuture = invokeFutureMap.remove(id);
            invokeFuture.putResponse(responseCommand);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        log.error("地址{}连接发生异常:", socketAddress, cause);
        connections.remove(AddressUtil.turnToAddress(socketAddress));
        ctx.close();
    }


}
